﻿using Interfaces.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Win32;
using Models;
using Newtonsoft.Json;
using Services;
using System.IO;
using System.Windows;
using System.Windows.Input;
using Utils;
using WorkPieceDataCapture;
using WorkPieceDataCapture.ViewModels;
using WorkPieceDataCapture.Views;

namespace ViewModels
{
    public class vm_WorkPieceDatacapture_Search : vm_Base
    {
        #region 全局变量与枚举
        private IServiceProvider _serviceProvider;
        WorkPieceDataCaptureRespository respository;
        List<tb_WorkPieceDataCapture_Realtime>? _list_History;
        public List<tb_WorkPieceDataCapture_Realtime>? list_History
        {
            get { return _list_History; }
            set
            {
                _list_History = value;
                OnPropertyChanged(nameof(list_History));
            }
        } //查询结果
        SearchSummary _searchSummary;
        public SearchSummary searchSummary
        {
            get { return _searchSummary; }
            set
            {
                _searchSummary = value;
                OnPropertyChanged(nameof(searchSummary));
            }
        } //查询结果统计
        #endregion
        #region 事件注册
        public ICommand RowDoubleClickCommand { get; set; }     //双击行显示明细事件
        public ICommand doSearchCommand { get; set; }   //执行查询事件
        public ICommand showSearchConditionCommand { get; set; }  //显示查询条件的事件
        public ICommand doExportListCommand { get; set; } //执行导出列表数据的事件
        public ICommand doExportDetailCommand { get; set; }  //执行导出明细数据的事件
        #endregion
        #region 构造与析构函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public vm_WorkPieceDatacapture_Search(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
            this.respository = new WorkPieceDataCaptureRespository(this._serviceProvider);
            RowDoubleClickCommand = new RelayCommand(ProduceRecordselected);    //绑定双击行看明细的事件注册
            doSearchCommand = new RelayCommand(doSearch);   //点击查询按钮的事件注册
            showSearchConditionCommand = new RelayCommand(ShowSearchCondition);   //点击查询按钮显示查询条件的事件注册
            doExportListCommand = new RelayCommand(doExportList);   //执行导出列表的事件注册
            doExportDetailCommand = new RelayCommand(doExportDetail);   //执行导出明细的事件注册
            initialize();
        }
        /// <summary>
        /// 析构函数
        /// </summary>
        ~vm_WorkPieceDatacapture_Search()
        {

        }
        #endregion
        #region 事件
        /// <summary>
        /// 类的初始化
        /// </summary>
        /// <returns></returns>
        public IFuncResult<string> initialize()
        {
            var result = new FuncResult<string>();
            try
            {

                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        /// <summary>
        /// 生产记录明细双击显示明细
        /// </summary>
        /// <param name="parameter"></param>
        private void ProduceRecordselected(object parameter)
        {
            // 这里处理选中行的逻辑
            // 参数 parameter 可以是 DataGridRow 或选中项的数据对象，取决于您如何设置 CommandParameter
            var model = parameter as tb_WorkPieceDataCapture_Realtime;
            if (model != null)
            {
                var detail = new ProduceDetail(model);
                detail.ShowDialog();
            }
        }
        /// <summary>
        /// 显示查询条件窗体
        /// </summary>a
        /// <param name="parameter"></param>
        private void ShowSearchCondition(object parameter)
        {
            SearchCondition searchCondition = new SearchCondition();
            searchCondition.ShowDialog();
            if (searchCondition.DialogResult == true)
            {
                doSearch(searchCondition.conditions);
            }
        }
        /// <summary>
        /// 执行数据查询
        /// </summary>
        /// <param name="parameter"></param>
        private void doSearch(object parameter)
        {
            try
            {
                var conditions = parameter as model_SearchCondition;
                var context = this._serviceProvider.GetService<AppDbContext>();
                if (context != null)
                {
                    if (conditions.dDate_Begin > conditions.dDate_End)
                    {
                        MessageBox.Show("开始日期不能大于结束日期！");
                        return;
                    }
                    var list_Final = new List<tb_WorkPieceDataCapture_Realtime>();    //存放最终结果
                    var list_FinalJson = new List<string>();    //存放不同实体类但是相同结构的数据的json
                    #region 如果查询的年月区间包含一个月以内的数据，则需要从实时表里查询数据
                    var nowYearMonth = DateTime.Now.ToString("yyyyMM");
                    if (int.Parse(nowYearMonth) >= int.Parse(conditions.dDate_Begin.Value.ToString("yyyyMM"))
                        && (int.Parse(nowYearMonth) <= int.Parse(conditions.dDate_End.Value.ToString("yyyyMM"))))
                    {                        
                        var result = this.respository.SearchDataFromRealTimeTable(conditions, context.tb_workpiecedatacapture_realtime);
                        if (result.bSuccess)
                        {
                            if (result.obj_Return.Count > 0)
                            {
                                list_Final.AddRange(result.obj_Return);
                            }
                        }
                        else
                        {
                            MessageBox.Show("从实时数据表中获取数据时出现错误！" + result.strMsg);
                            return;
                        }
                    }
                    #endregion
                    #region 根据起始日期到结束日期的年份确认用到的历史表并执行查询（动态方式）
                    for (var i = conditions.dDate_Begin.Value.Year; i <= conditions.dDate_End.Value.Year; i++)
                    {
                        // 使用新的动态查询方法
                        var yearResult = respository.SearchDataFromHistoryTableByYear(i, conditions);
                        if (yearResult.bSuccess)
                        {
                            yearResult.obj_Return.ForEach(ee =>
                            {
                                list_FinalJson.Add(JsonConvert.SerializeObject(ee));
                            });
                        }
                        else
                        {
                            MessageBox.Show($"从{i}年历史表中获取数据时出现错误！" + yearResult.strMsg);
                            return;
                        }
                    }
                    #endregion
                    list_FinalJson.ForEach(ee =>
                    {
                        list_Final.Add(JsonConvert.DeserializeObject<tb_WorkPieceDataCapture_Realtime>(ee));
                    });
                    int increment = 1;
                    foreach (var item in list_Final)
                    {
                        item.iID = increment++;
                    }
                    list_History = list_Final;
                    if (list_History.Count > 0)
                    {
                        var Summary = new SearchSummary();
                        Summary.RecordCount = list_Final.Count;
                        Summary.ZC_OK = list_Final.Where(ee => ee.ZC_Result == "OK").Count();
                        Summary.ZC_NG = list_Final.Where(ee => ee.ZC_Result == "NG").Count();
                        Summary.YCQ_OK = list_Final.Where(ee => ee.FLJ_YCQ_Result == "OK").Count();
                        Summary.YCQ_NG = list_Final.Where(ee => ee.FLJ_YCQ_Result == "NG").Count();
                        Summary.GLH_OK = list_Final.Where(ee => ee.FLJ_GLH_Result == "OK").Count();
                        Summary.GLH_NG = list_Final.Where(ee => ee.FLJ_GLH_Result == "NG").Count();
                        Summary.ECQ_OK = list_Final.Where(ee => ee.FLJ_ECQ_Result == "OK").Count();
                        Summary.ECQ_NG = list_Final.Where(ee => ee.FLJ_ECQ_Result == "NG").Count();
                        Summary.KZH_OK = list_Final.Where(ee => ee.FLJ_ECQ_Result == "OK").Count();
                        Summary.KZH_NG = list_Final.Where(ee => ee.FLJ_ECQ_Result == "NG").Count();
                        Summary.SK_OK = list_Final.Where(ee => ee.FLJ_SK_Result == "OK").Count();
                        Summary.SK_NG = list_Final.Where(ee => ee.FLJ_SK_Result == "NG").Count();
                        Summary.NM_OK = list_Final.Where(ee => ee.FLJ_NM_Result == "OK").Count();
                        Summary.NM_NG = list_Final.Where(ee => ee.FLJ_NM_Result == "NG").Count();
                        Summary.QM_OK = list_Final.Where(ee => ee.JCY_QM_Result == "OK").Count();
                        Summary.QM_NG = list_Final.Where(ee => ee.JCY_QM_Result == "NG").Count();
                        Summary.WM_OK = list_Final.Where(ee => ee.FLJ_WM_Result == "OK").Count();
                        Summary.WM_NG = list_Final.Where(ee => ee.FLJ_WM_Result == "NG").Count();
                        Summary.KTQM_OK = list_Final.Where(ee => ee.JCY_KTQM_Result == "OK").Count();
                        Summary.KTQM_NG = list_Final.Where(ee => ee.JCY_KTQM_Result == "NG").Count();
                        Summary.ZC_Percent = MathMethods.CalculatePercentage(Summary.ZC_OK, Summary.RecordCount);
                        Summary.YCQ_Percent = MathMethods.CalculatePercentage(Summary.YCQ_OK, Summary.RecordCount);
                        Summary.GLH_Percent = MathMethods.CalculatePercentage(Summary.GLH_OK, Summary.RecordCount);
                        Summary.ECQ_Percent = MathMethods.CalculatePercentage(Summary.ECQ_OK, Summary.RecordCount);
                        Summary.KZH_Percent = MathMethods.CalculatePercentage(Summary.KZH_OK, Summary.RecordCount);
                        Summary.SK_Percent = MathMethods.CalculatePercentage(Summary.SK_OK, Summary.RecordCount);
                        Summary.NM_Percent = MathMethods.CalculatePercentage(Summary.NM_OK, Summary.RecordCount);
                        Summary.QM_Percent = MathMethods.CalculatePercentage(Summary.QM_OK, Summary.RecordCount);
                        Summary.WM_Percent = MathMethods.CalculatePercentage(Summary.WM_OK, Summary.RecordCount);
                        Summary.KTQM_Percent = MathMethods.CalculatePercentage(Summary.KTQM_OK, Summary.RecordCount);
                        this.searchSummary = Summary;
                    }
                    else
                    {
                        this.searchSummary = new SearchSummary();
                    }
                }
                else
                {
                    MessageBox.Show("当前无法连接到数据库，请重试一次");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行查询操作发生异常！\n" + ex.Message);
            }
        }
        /// <summary>
        /// 执行导出列表数据
        /// </summary>
        /// <param name="parameter"></param>
        private void doExportList(object parameter)
        {
            if (this.list_History == null || this.list_History.Count == 0) return;
            string strNewFileName = "";
            try
            {
                //将模板文件复制一份
                strNewFileName = AppDomain.CurrentDomain.BaseDirectory + "Files\\" + Guid.NewGuid().ToString().Replace("-", "") + ".xlsx";
                File.Copy(AppDomain.CurrentDomain.BaseDirectory + "Files\\ExportListTemplate.xlsx", strNewFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("复制模板到新文件出错！\n" + ex.Message);
                return;
            }
            try
            {
                var helper = new ExcelHelper();
                helper.WriteEntityListToExcel(this.list_History, strNewFileName, "Sheet1", GlobalClass.dic_ExportColumnRelation, 2);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件到Excel出错！\n" + ex.Message);
                return;
            }
            try
            {
                SaveFileDialog dialog = new SaveFileDialog();
                if (dialog.ShowDialog() == true)
                {
                    if (!dialog.FileName.Contains(".xlsx"))
                    {
                        File.Move(strNewFileName, dialog.FileName + ".xlsx");
                    }
                    else
                    {
                        File.Move(strNewFileName, dialog.FileName);
                    }
                    MessageBox.Show("导出成功");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("将导出的Excel移动到目标文件夹出错！\n" + ex.Message);
                return;
            }
        }
        /// <summary>
        /// 执行导出明细
        /// </summary>
        /// <param name="parameter"></param>
        private void doExportDetail(object parameter)
        {
            var obj = parameter as tb_WorkPieceDataCapture_Realtime;
            if (obj != null)
            {
                string strNewFileName = "";
                try
                {
                    //将模板文件复制一份
                    strNewFileName = AppDomain.CurrentDomain.BaseDirectory + "Files\\" + Guid.NewGuid().ToString().Replace("-", "") + ".xlsx";
                    File.Copy(AppDomain.CurrentDomain.BaseDirectory + "Files\\ExportDetailTemplate.xls", strNewFileName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("复制模板到新文件出错！\n" + ex.Message);
                    return;
                }
                try
                {
                    var helper = new ExcelHelper();
                    helper.WriteEntityDetailToExcel(obj, strNewFileName, "Sheet1", GlobalClass.dic_ExportDetailRelation);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("导出文件到Excel出错！\n" + ex.Message);
                    return;
                }
                try
                {
                    SaveFileDialog dialog = new SaveFileDialog();
                    if (dialog.ShowDialog() == true)
                    {
                        if (!dialog.FileName.Contains(".xls"))
                        {
                            File.Move(strNewFileName, dialog.FileName + ".xls");
                        }
                        else
                        {
                            File.Move(strNewFileName, dialog.FileName);
                        }
                        MessageBox.Show("导出成功");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("将导出的Excel移动到目标文件夹出错！\n" + ex.Message);
                    return;
                }
            }
        }
        #endregion
        #region 方法

        #endregion
    }
}
